<template>
    <div>
        <el-form :model="form" label-width="150px" ref="form">
            <el-form-item label="用户">
                <el-input placeholder="请输入用户" style="width: 500px" :disabled="true" v-model="name"></el-input>
            </el-form-item>

            <el-form-item label="类型">
                <el-select placeholder="选择类型" style="width: 500px;" v-model="form.creation_type"
                    @change="creation_typeChange">
                    <el-option :key="item.value" :label="item.name" :value="item.value"
                        v-for="item in typeList"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="作品名">
                <el-input placeholder="请输入作品名" style="width: 500px" v-model="form.creation_name"></el-input>
            </el-form-item>

            <el-form-item label="标签(非必传)">
                <el-tag :key="tag" v-for="tag in form.labels" closable :disable-transitions="false"
                    @close="handleClose(tag)">
                    {{ tag }}
                </el-tag>
                <el-input class="input-new-tag" v-if="inputVisible" style="width: 200px" v-model="inputValue"
                    ref="saveTagInput" size="small" placeholder="回车提交" @keyup.enter.native="handleInputConfirm"
                    @blur="handleInputConfirm">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加标签</el-button>
            </el-form-item>

            <el-form-item label="价格" v-if="form.creation_type == 'long'">
                <el-input placeholder="请输入价格" style="width: 500px" v-model="form.fee"></el-input>
            </el-form-item>

            <el-form-item label="作品集数（第几集）" v-if="form.creation_type == 'long'">
                <el-input placeholder="请输入作品集数" style="width: 500px" v-model="form.episode"></el-input>
            </el-form-item>

            <el-form-item label="上传的合集" v-if="form.creation_type == 'long'">
                <el-button v-if="!form.collection_id" class="button-new-tag" size="small"
                    @click="selectFun">点击选择合集</el-button>
                <div @click="selectFun" style="cursor: pointer;" v-else>{{ collection_name }}</div>
            </el-form-item>

            <!-- <el-form-item label="类型" v-if="form.creation_type == 'long'">
                <template>
                    <el-radio v-model="form.done" :label="1">已完结</el-radio>
                    <el-radio v-model="form.done" :label="0">未完结</el-radio>
                </template>
            </el-form-item> -->

            <el-form-item label="类型" v-if="form.creation_type == 'short'">
                <template>
                    <el-radio v-model="form.is_teenager" :label="0">非青少年视频 </el-radio>
                    <el-radio v-model="form.is_teenager" :label="1">青少年模式视频</el-radio>
                </template>
            </el-form-item>

            <el-form-item label="封面图" v-if="form.creation_type == 'long'">
                <medium v-model="form.first_frame" size="300"></medium>
            </el-form-item>

            <el-form-item label="上传视频">
                <el-upload :accept="videoAccept" :auto-upload="false" :disabled="loading" :on-change="toUpload"
                    action="#999" class="upload-demo" drag v-if="!file_url">
                    <div class="mt-60">
                        <el-image :src="icon_url" fit="contain" style="width: 60px"></el-image>
                        <div class="color-999 font-15 pr-4" v-if="!loading">添加视频</div>
                        <div class="color-999 font-15 pr-4" v-else>上传中...(进度{{ percent }}%)</div>
                    </div>
                </el-upload>
                <div class="position-relative display-inline" v-else>
                    <video :src="file_url" class="el-upload-dragger" controls ref="video"></video>
                    <i @click="removeFile" class="el-icon el-icon-delete delete-video cursor-pointer"></i>
                </div>
            </el-form-item>

            <!-- <el-form-item label="上传视频"  v-if="form.creation_type == 'short'">
                <div>
                    <el-upload class="avatar-uploader" :action="uploadUrl + '/upload/create'" :data="{ file_type: 'video' }"
                        v-bind:on-progress="uploadVideoProcess" v-bind:on-success="handleVideoSuccess"
                        v-bind:before-upload="beforeUploadVideo" v-bind:show-file-list="false" :headers="{
                            Authorization: 'Bearer ' + $store.state.user.token,
                        }">
                        <video v-if="videoForm.showVideoPath != '' && !videoFlag" v-bind:src="videoForm.showVideoPath"
                            class="avatar video-avatar" controls="controls">
                            您的浏览器不支持视频播放
                        </video>
                        <i v-else-if="videoForm.showVideoPath == '' && !videoFlag"
                            class="el-icon-plus avatar-uploader-icon"></i>
                        <el-progress v-if="videoFlag == true" type="circle" v-bind:percentage="videoUploadPercent"
                            style="margin-top: 7px"></el-progress>
                    </el-upload>
                </div>
            </el-form-item> -->

            <el-form-item label="是否广告" v-if="form.creation_type == 'short'">
                <template>
                    <el-radio v-model="isAdvertisement" :label="0">否 </el-radio>
                    <el-radio v-model="isAdvertisement" :label="1">是</el-radio>
                </template>
            </el-form-item>

            <el-form-item label="长视频版权" v-if="form.creation_type == 'long'" size="300">


                <div class="pb-10" style="display: flex;flex-wrap: wrap;">
                    <div :key="index" style="margin-top: 4px;width: 150px;;margin-right: 20px;"
                        v-for="(item, index) in form.copyright">
                        <el-card :body-style="{ padding: '5px' }">
                            <el-image :preview-src-list="form.copyright" :src="item" :z-index="999" fit="contain"
                                style="width: 100%; height: 100px" />
                            <div>
                                <el-row>
                                    <el-col :span="24" class="col-do">
                                        <el-button @click="avatarDel(index)" size="medium" style="margin-right: 10px;"
                                            type="text">删除</el-button>
                                    </el-col>
                                </el-row>
                            </div>
                        </el-card>
                    </div>
                    <div>
                        <medium :isShow="false" @set-content="setCopyright"></medium>
                    </div>
                </div>
            </el-form-item>


            <el-form-item label="广告标题" v-if="isAdvertisement && form.creation_type == 'short'" size="300">
                <el-input placeholder="请输入广告标题" style="width: 500px" v-model="form.ad_name"></el-input>
            </el-form-item>

            <el-form-item label="广告描述" v-if="isAdvertisement && form.creation_type == 'short'" size="300">
                <el-input placeholder="请输入广告描述" style="width: 500px" v-model="form.ad_desc"></el-input>
            </el-form-item>

            <el-form-item label="广告外部链接" v-if="isAdvertisement && form.creation_type == 'short'" size="300">
                <el-input placeholder="请输入广告外部链接" style="width: 500px" v-model="form.ad_url"></el-input>
            </el-form-item>

            <el-form-item label="广告链接类型" v-if="isAdvertisement && form.creation_type == 'short'">
                <template>
                    <el-radio v-model="form.ad_type" label="outside">外部</el-radio>
                    <el-radio v-model="form.ad_type" label="inside">内部</el-radio>
                </template>
            </el-form-item>

            <el-form-item label="广告图标" v-if="isAdvertisement && form.creation_type == 'short'" size="300">
                <medium v-model="form.ad_icon"></medium>
            </el-form-item>

            <el-form-item label="广告结束时间" v-if="isAdvertisement && form.creation_type == 'short'" size="300">
                <el-date-picker v-model="form.ad_end_time" type="date" placeholder="选择广告结束时间" value-format="yyyy-MM-dd">
                </el-date-picker>
            </el-form-item>



            <el-form-item>
                <el-button type="primary" style="width: 470px; margin: 30px auto" :loading="submitComplete"
                    @click="submit">{{ type == 'create' ? '上传作品' : '修改作品' }}</el-button>
            </el-form-item>
        </el-form>

        <el-dialog :visible.sync="visible" title="选择合集" width="1000px">
            <el-form :model="form">

                <el-form-item label="分类">
                    <el-input clearable placeholder="请输入名称" size="small" style="width: 200px;"
                        v-model="parameter.name"></el-input>
                    <el-button @click="getWorksList()" size="small" type="primary" style="margin-left: 30px;">搜索</el-button>
                </el-form-item>

                <div>
                    <el-table :data="worksList" max-height="550px" size="small" style="width: 100%">
                        <el-table-column label="" prop="suggest_id" width="50px" v-if="visible">
                            <template slot-scope="scope">
                                <!-- <el-checkbox
                                    @change="handleCheckedCitiesChange($event, scope.row.collection_id)"></el-checkbox> -->
                                <el-radio :label="scope.row.collection_id" @change="handleCheckedCitiesChange(scope.row)"
                                    v-model="checked"></el-radio>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column label="ID" prop=""></el-table-column> -->
                        <el-table-column label="作品名" prop="name"></el-table-column>
                        <el-table-column label="图片" prop="thumbnail">
                            <template slot-scope="scope">
                                <el-image class="border" style="width: 50px; height: 50px" :src="scope.row.thumbnail"
                                    :preview-src-list="toArray(scope.row.thumbnail)">
                                </el-image>
                            </template>
                        </el-table-column>
                        <el-table-column label="发布人" prop="user_id">
                            <template slot-scope="scope">
                                <UserInfo :user_id="scope.row.user_id" :userInfos="scope.row.author_info"
                                    v-if="scope.row.user_id" :modalShow="false"></UserInfo>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <div class="block" style="margin-left: 40%;margin-top: 50px;">
                    <el-pagination layout="prev, pager, next" :total="totals" @size-change="sizeChange"
                        @prev-click="prevClick" @next-click="nextClick" @current-change="currentChange">
                    </el-pagination>
                </div>
            </el-form>
            <div class="dialog-footer" slot="footer">
                <el-button @click="closeBox">取 消</el-button>
                <el-button @click="visible = false" type="primary">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
  
<script>
import medium from "@/components/medium/index";
import initData from '@/mixins/upload'

import JSEncrypt from "jsencrypt";
import config from "@/utils/config";
export default {
    mixins: [initData],
    components: {
        medium,
    },
    computed: {
        headers() {
            return {
                Authorization: "Bearer " + this.$store.state.user.token,
            };
        },
    },
    data() {
        return {
            form: {
                user_id: '',
                creation_name: "",
                media_urls: [], //媒体地址数组
                first_frame: '', //首帧图片 (不必传)
                fee: '0.00', //作品价格非必传
                creation_type: "", //long长视频short短视频
                labels: [], //"标签 (不必传)"
                collection_id: null, //合集ID (长视频类型时必传)
                episode: null, //合集集数 (长视频类型时必传)
                //  done: null, //1已完结 0未完结 (不必传 关于长视频)
                copyright: [], //长视频版权 (长视频时必传)
                is_teenager: null, //(短视频必传) 0非青少年视频 1青少年模式视频
                media_duration: '', //时长
                height: '',
                width: '',
                ad_url: '',//短视频广告链接(只能短视频类型可填
                ad_name: '',//广告标题
                ad_desc: '',//广告描述
                ad_icon: '',//广告图片
                ad_type: '',//链接类型
                is_ad: 0, //是否广告
                ad_end_time:'',//广告结束时间
                ad_space: 'short'
            },
            icon_url: require('@/assets/image/upload-video-icon.png'),
            upload_icon: require('@/assets/image/upload-video-icon.png'),
            collection_name: "",
            file: null,
            fileList: [],
            videoFlag: false,
            //是否显示进度条
            videoUploadPercent: "",
            //进度条的进度，
            isShowUploadVideo: false,
            //显示上传按钮
            videoForm: {
                showVideoPath: "", //回显的变量
            },
            isAdvertisement: 0,//0不是广告，1是广告
            inputVisible: false,
            inputValue: '',
            typeList: [
                {
                    name: '长视频',
                    value: 'long',
                },
                {
                    name: '短视频',
                    value: 'short',
                },
            ],
            name: '',
            parameter: {
                page: 1,
                size: 10,
                name: "",
                user_id: ''
            },
            visible: false,
            worksList: [],
            totals: 0,
            checked: 0,
            uploadUrl: '',
            type: 'create',
            submitComplete: false,
        };
    },
    mounted() {
        if (this.$route.query.user_id) {
            this.getUserList(this.$route.query.user_id);
        }
        this.uploadUrl = process.env.VUE_APP_API_URL

        if (this.$route.query.creation_id) {
            this.type = this.$route.query.type
            this.getCreationInfo(this.$route.query.creation_id)
        }
        if (this.$route.query.user_id) {
            this.parameter.user_id = this.$route.query.user_id
        }

        //console.log(,999)
    },

    methods: {
        setCopyright(value) {
            //this.thumbnail = value
            console.log('value', value)
            this.form.copyright.push(value)
            console.log('this.form.copyright', this.form.copyright)
        },
        avatarDel(index) {
            this.form.copyright.splice(index, 1)
        },
        creation_typeChange(res) {
            if (res == 'long') {
                this.bucket = null
            } else {
                this.bucket = res
            }
        },
        handleClose(tag) {
            this.form.labels.splice(this.form.labels.indexOf(tag), 1);
        },
        toArray(str) {
            const arr = []
            arr.push(str)
            return arr
        },
        selectFun() {
            this.getWorksList()
            this.visible = true
        },

        removeFile() {
            this.$confirm('确认要删除上传的此文件吗', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.file_url = ''
                    this.$message({
                        type: 'success',
                        message: '删除成功!',
                    })
                })
                .catch(() => { })
        },

        //上传前回调
        beforeUploadVideo(file) {
            var fileSize = file.size / 1024 / 1024 < 50; //控制大小  修改50的值即可
            if (
                [
                    "video/mp4",
                    "video/ogg",
                    "video/flv",
                    "video/avi",
                    "video/wmv",
                    "video/rmvb",
                    "video/mov",
                ].indexOf(file.type) == -1 //控制格式
            ) {
                this.$message.error("请上传正确的视频格式");
                return false;
            }
            if (!fileSize) {
                this.$message.error("视频大小不能超过50MB");
                return false;
            }
            this.isShowUploadVideo = false;
        },

        //进度条
        uploadVideoProcess(event, file, fileList) {
            //注意在data中添加对应的变量名
            this.videoFlag = true;
            this.videoUploadPercent = file.percentage.toFixed(0) * 1;
        },

        //上传成功回调
        handleVideoSuccess(res, file) {
            let decrypt = new JSEncrypt();
            decrypt.setPrivateKey(config.cert.privateKey);
            var decryptMsg = decrypt.decryptLong(res, "utf-8");
            res = JSON.parse(decryptMsg);
            this.isShowUploadVideo = true;
            this.videoFlag = false;
            this.videoUploadPercent = 0;
            console.log("成功", res);
            //后台上传数据
            if (res.code == 200) {
                this.videoForm.showVideoPath = res.data[0].full_path; //上传成功后端返回视频地址 回显
                this.form.media_urls[0] = res.data[0].full_path;
            } else {
                this.$message.error("上传失败！");
            }
        },

        uploadFiles(fileData) {
            let that = this;
            this.$request
                .post("/upload/create", { file_type: "video", file: fileData })
                .then((res) => {
                    console.log("上传视频", res);
                });
        },

        getSystemNoticeDetails(id) {
            let that = this;
            this.$request.get("/system/notification/get/" + id).then((res) => {
                that.datas = res;
                console.log("getSystemNoticeDetails", res);
            });
        },

        showInput() {
            this.inputVisible = true;
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },

        handleInputConfirm() {
            let inputValue = this.inputValue;
            if (inputValue) {
                this.form.labels.push(inputValue);
            }
            this.inputVisible = false;
            this.inputValue = '';
        },


        sizeChange(val) {
            console.log(val)
        },

        currentChange(val) {
            console.log(val)
            this.parameter.page = val
            this.getWorksList()
        },
        prevClick(val) {
            console.log(val)
        },

        nextClick(val) {
            console.log(val)
        },

        getWorksList(id) {
            this.$request.get('/creation-collection/index', this.parameter).then((res) => {
                this.totals = res.page.total
                this.worksList = res.items
            })
        },

        closeBox() {
            this.visible = false
            this.form.collection_id = ''
            this.checked = 0
        },

        handleCheckedCitiesChange(event) {
            console.log("value", event)
            this.form.collection_id = event.collection_id
            this.collection_name = event.name
            console.log(this.form.collection_id)
        },


        getUserList(user_id) {
            let that = this
            this.$request.get('/user/index', { page: 1, size: 10, id: user_id }).then((res) => {
                console.log(res.items[0], 111)
                this.form.user_id = res.items[0].id
                that.name = res.items[0].name

                // this.init()
            })
        },


        getCreationInfo(id) {
            let that = this
            this.$request.get('/creation/info', { creation_id: id }).then((res) => {
                console.log('res', res)
                that.form = res
                that.collection_name = res.collection.name
            })
        },


        //提交
        submit() {
            if (this.submitComplete) return
            this.submitComplete = true
            this.form.media_urls[0] = this.file_url
            this.form.media_duration = this.duration
            this.form.height = this.height
            this.form.width = this.width
            console.log('this.form', this.form)
            if (this.form.creation_type == 'long') {
                delete this.form.ad_url //长视频不上传这些字段
                delete this.form.ad_name //长视频不上传这些字段
                delete this.form.ad_desc //长视频不上传这些字段
                delete this.form.ad_image_url //长视频不上传这些字段
                delete this.form.ad_type //长视频不上传这些字段
                delete this.form.is_teenager //长视频不上传这些字段
                delete this.form.is_ad //长视频不上传这些字段
                delete this.form.ad_space //长视频不上传这些字段
                delete this.form.ad_end_time //长视频不上传这些字段
                // this.form.copyright = this.form.copyright
                if (this.form.media_duration < 180) {
                    this.$message({
                        message: "上传长视频时长不能小于3分钟！",
                        type: "warning",
                    });
                    this.submitComplete = false
                    return;
                }
                if (
                    !(
                        this.form.creation_name &&
                        this.form.collection_id &&
                        this.form.episode &&
                        this.form.copyright
                    )
                ) {
                    this.$message({
                        message: "请将信息填写完整！",
                        type: "warning",
                    });
                    this.submitComplete = false
                    return;
                }

            } else {
                // 短视频
                //短视频不上传这些字段
                this.form.is_ad = this.isAdvertisement
                delete this.form.collection_id
                delete this.form.episode
                delete this.form.copyright
                if (this.form.media_duration > 600) {
                    this.$message({
                        message: "上传短视频时长不能大于10分钟！",
                        type: "warning",
                    });
                    this.submitComplete = false
                    return;

                }

                if (this.type != 'update') {
                    this.form.first_frame = this.first_frame //自动赋值给短视频封面
                }

                console.log('this.form.first_frame', this.form.first_frame)
            }

            if (!this.form.creation_type) {
                this.$message({
                    message: "请将上传视频类型！",
                    type: "warning",
                });
                this.submitComplete = false
                return;
            }

            if (this.type == 'create') {
                this.$request.post("/creation/create", this.form).then((res) => {
                    this.$message({
                        message: "发布成功",
                        type: "success",
                    });
                    this.submitComplete = false
                    if (this.form.creation_type == 'long') {
                        this.$router.push({ path: "/long-video-process" });
                    } else {
                        this.$router.push({ path: "/short-video" });
                    }
                    //  this.closeBox();
                }).catch((error) => {
                    this.submitComplete = false
                });
            } else {
                this.$request.put("/creation/update/" + this.form.creation_id, this.form).then((res) => {
                    this.$message({
                        message: "修改成功",
                        type: "success",
                    });

                    if (this.form.creation_type == 'long') {
                        this.$router.push({ path: "/long-video-details?id=" + this.form.collection.collection_id });
                    } else {
                        this.$router.push({ path: "/short-video" });
                    }
                }).catch((error) => {
                    this.submitComplete = false
                });

            }
        }
    }
};
</script>
  
<style lang="scss" scoped>
.avatar-uploader-icon {
    border: 1px dashed #d9d9d9 !important;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px !important;
    position: relative !important;
    overflow: hidden !important;
}

.avatar-uploader .el-upload:hover {
    border: 1px dashed #d9d9d9 !important;
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 300px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 300px;
    height: 178px;
    display: block;
}
</style>